﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Data;
using Maticsoft.Common;

namespace lcs.Web.tenderExpert
{
    public partial class RandomExpert : System.Web.UI.Page
    {
        Maticsoft.BLL.expertConfirm excm = new Maticsoft.BLL.expertConfirm();
        Maticsoft.BLL.expertInfo exm = new Maticsoft.BLL.expertInfo();
        Maticsoft.BLL.superviseConfirm sm = new Maticsoft.BLL.superviseConfirm();

        lcs.BLL.user um = new BLL.user();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindDDl();
                BindData();
            }
        }

        protected void Timer1_Tick(object sender, EventArgs e)
        {
            DataSet ds_yes = excm.GetList(" status = 1  and  tenderNum='" + this.txt_zbbh.Text + "'");//审核通过
            DataSet ds_no = excm.GetList(" status = 2  and  tenderNum='" + this.txt_zbbh.Text + "'");//审核未通过
            DataSet ds_wsh = excm.GetList(" status = 0  and  tenderNum='" + this.txt_zbbh.Text + "'");//未审核

            if (ds_yes.Tables[0].Rows.Count > 0)
            {
                this.lbl_result.Text = "审核通过！";
                this.pnl_cz.Visible = true;
                this.pnl_no.Visible = false;
                this.Timer1.Enabled = false;
            }
            else if (ds_no.Tables[0].Rows.Count > 0 )
            {
                this.pnl_cz.Visible = false;
                this.pnl_no.Visible = true;
                this.btn_confirm.Enabled = true;
                this.lbl_warnNo.Text = "专家审核未通过，请重新抽取专家!";
             
                this.Timer1.Enabled = true;
            }
            else
            {
                this.pnl_cz.Visible = false;
            }
            //如果有未审核且有审核未通过对记录则判断为重新提交了抽选结果
            if (ds_no.Tables[0].Rows.Count > 0 && ds_wsh.Tables[0].Rows.Count > 0)
            {
                this.pnl_cz.Visible = false;
                this.pnl_no.Visible = false;
                
                this.Timer1.Enabled = true;
            }
        
        }
        public void BindData()
        {
            DataSet ds = excm.GetList(" status = 0  and  tenderNum='"+this.txt_zbbh.Text+"'");
   
            this.gridView.DataSource = ds;
            this.gridView.DataBind();
        
        }
        public void BindDDl()
        {
            DataSet ds_user = um.GetList(" roles_id = 17 ");//纪委监督员角色ID为17

            this.ddljwjdy.DataSource = ds_user;
            this.ddljwjdy.DataTextField = "user_name";
            this.ddljwjdy.DataValueField = "user_id";
            this.ddljwjdy.DataBind();
        }

        //抽取专家按钮
        protected void btn_confirm_Click(object sender, EventArgs e)
        {
            if (this.cblexpertMajor.SelectedIndex < 0)
            {
                Maticsoft.Common.MessageBox.Show(this, "请选择专家所属专业");
                return;
            }

            string projectName = this.txt_projectName.Text;
            int JScount = int.Parse(this.txt_randomJSCount.Text);//技术专家人数
            int SWcount = int.Parse(this.txt_randomSWCount.Text);//商务专家人数
            string tenderNum = this.txt_zbbh.Text;
            int jwUid = int.Parse(this.ddljwjdy.SelectedItem.Value);
            string jwUname = this.ddljwjdy.SelectedItem.Text;

            string selExpertMajor = "";//选取的专家专业信息
            for (int i = 0; i < cblexpertMajor.Items.Count; i++)
            {
                if (cblexpertMajor.Items[i].Selected)
                {
                    string selValue = cblexpertMajor.Items[i].Value;
                    if (selValue == "10KV配电")
                    {
                        selValue = "s10KV配电";
                    }

                    selExpertMajor += selValue + ",";
                }
            }
            selExpertMajor = selExpertMajor.Substring(0, selExpertMajor.LastIndexOf(","));


            if (Session["login"] != null)
            {
                DataSet ds = Session["login"] as DataSet;

                string randomName = ds.Tables[0].Rows[0]["user_name"].ToString();
                int randomId = int.Parse(ds.Tables[0].Rows[0]["user_id"].ToString());
                bool isS = false;
                if (this.rdo_yes.Checked)
                {
                    isS = true;
                }

                string msg = RandomExperts(projectName, JScount, SWcount, tenderNum, jwUid, jwUname, selExpertMajor, randomName, randomId, isS);
                if (!string .IsNullOrEmpty(msg))
                {
                    //Maticsoft.Common.MessageBox.Show(this, msg);
                    this.lbl_warn.Text = msg;
                    this.lbl_warn.Visible = true;
                }
                else
                {
                    BindData();
                    this.btn_confirm.Visible = false;
                    this.lbl_warn.Visible = false;
                }
            }

           
        }

        //抽取专家并写入数据库
        private string  RandomExperts(string projectName, int JScount, int SWcount, string tenderNum, int jwUid, string jwUname, 
            string selExpertMajor,string randomName,int randomId,bool isS)
        {
            string  msg = "";
           

            #region 筛选出符合专业的技术专家
            DataSet ds_js = SelectJS(selExpertMajor,isS);

            if (JScount > ds_js.Tables[0].Rows.Count)
            {
                msg = "抽取符合条件的技术专家数量大于专家库专家数量，请降低选取人数。\n";
            }
            else
            {
                Maticsoft.Model.expertConfirm exc = new Maticsoft.Model.expertConfirm();
                exc.tenderNum = tenderNum;
                exc.projectname = projectName;
                exc.randomName = randomName;
                exc.randomId = randomId;
                exc.time = DateTime.Now;
                exc.superviseId = jwUid;
                exc.superviseName = jwUname;

                // 抽取技术专家
                RandomExpertDS(ds_js, JScount, exc, false);

                #region 筛选出商务专家

                DataSet ds_sw = null;

                int s = 0;
                if (isS)
                {
                    s = 1;
                }

                string strSql = " 商务综合 = 1 and isUse = 0 and 安全工具=" + s;

                ds_sw = exm.GetList(strSql);

                if (SWcount < ds_sw.Tables[0].Rows.Count)
                {
                    Maticsoft.Model.expertConfirm excsw = new Maticsoft.Model.expertConfirm();
                    excsw.tenderNum = tenderNum;
                    excsw.projectname = projectName;
                    excsw.randomName = randomName;
                    excsw.randomId = randomId;
                    excsw.time = DateTime.Now;
                    excsw.superviseId = jwUid;
                    excsw.superviseName = jwUname;

                    // 抽取商务专家
                    RandomExpertDS(ds_sw, SWcount, excsw, true);
                }
                else
                {
                    //更新已被抽取的技术专家使用状态为false
                    DataSet ds_excm = excm.GetList(" tenderNum='" + tenderNum + "' and status = 0 ");

                    if (ds_excm.Tables[0].Rows.Count > 0)
                    {
                        foreach (DataRow row in ds_excm.Tables[0].Rows)
                        {
                            int expertInfoId = Convert.ToInt32(row["expertInfoId"]);

                            Maticsoft.Model.expertInfo ex = exm.GetModel(expertInfoId);

                            ex.isUse = false;
                            exm.Update(ex);
                        }
                    }
                    excm.DeleteListByWhere(" tenderNum='" + tenderNum + "' and status = 0 ");//删除所有招标编号为此次抽选的数据状态为缓存的记录

                    msg = "抽取符合条件的商务专家数量大于专家库专家数量，请降低选取人数。";

                }



                #endregion
            }
            #endregion

            return msg;
        }

        //筛选出符合专业的技术专家
        private DataSet SelectJS(string selExpertMajor,bool isS)
        {
            int s = 0;
            if (isS)
            {
                s = 1;
            }

            DataSet ds = null;
            string[] selExpertMajors = selExpertMajor.Split(',');

            string strSql = " ";

            if (selExpertMajors.Length == 1)//判断如果只选择了一个专业
            {
                if (selExpertMajors[0] == "商务综合")//而且这个专业是"商务综合" 
                {
                    strSql = " expertName = '' and 安全工具= " + s;//让sql语句找不到任何记录
                }
                else
                {
                    strSql += " (";
                    if (selExpertMajors[0] != "商务综合")
                    {
                        strSql += selExpertMajors[0] + "= 1 and ";
                    }
                    strSql = strSql.Substring(0, strSql.LastIndexOf("and"));
                    strSql += ") and isUse = 0 and 安全工具=" + s;
                }
               
            }
            else
            {
                strSql += " (";
                foreach (string str_selExpertMajor in selExpertMajors)
                {
                    if (str_selExpertMajor != "商务综合")
                    {
                        strSql += str_selExpertMajor + "= 1 and ";
                    }
                }
                strSql = strSql.Substring(0, strSql.LastIndexOf("and"));
                strSql += ") and isUse = 0 and 安全工具=" + s;
            }

            ds = exm.GetList(strSql);
            return ds;
        }

        //抽取专家
        private DataTable RandomExpertDS(DataSet ds, int count,Maticsoft.Model.expertConfirm exc,bool isSW)
        {
            DataTable re_ds = ds.Tables[0].Clone();
            List<int> li_result = new List<int>();//抽取结果
            List<int> li_source = new List<int>();

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                li_source.Add(Convert.ToInt32(row["expertInfoId"]));
            }


            Random rand = new Random();

            int i = 0;
            while (i < count)
            {
                int index = rand.Next(0, li_source.Count);
                if (!li_result.Contains(li_source[index]))
                {
                    li_result.Add(li_source[index]);
                    i++;
                }
            }

            for (int j = 0; j < li_result.Count; j++)
            {
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    if (Convert.ToInt32(row["expertInfoId"]) == li_result[j])
                    {
                        re_ds.ImportRow(row);

                        int expertInfoId = Convert.ToInt32(row["expertInfoId"]);

                        Maticsoft.Model.expertInfo ex = exm.GetModel(expertInfoId);

                        ex.isUse = true;//更新专家使用状态为true

                        exm.Update(ex);

                        if (isSW)//抽取的商务专家
                        {
                            exc.sExpertrName = row["expertName"].ToString();
                        }
                        else//抽取的技术专家
                        {
                            exc.jExpertName = row["expertName"].ToString();
                        }
                        exc.expertInfoId = expertInfoId;
                        exc.status = 0;//缓存抽取结果
                        excm.Add(exc);
                    }
                }
            }


            return re_ds;
        }

        //是否重新抽选
        protected void ddl_isReRandom_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddl_isReRandom.SelectedValue == "是")
            {
                this.gridView.Columns[0].Visible = true;
                this.btn_ReRandom.Visible = true;
            }
            else
            {
                this.gridView.Columns[0].Visible = false;
                this.btn_ReRandom.Visible = false;
            }
        }
        //重新抽选
        protected void btn_ReRandom_Click(object sender, EventArgs e)
        {
            string [] idLists = GetSelIDlist().Split('|');

            if (idLists.Length == 3)
            {
                string idList = idLists[0];
                int JScount = Convert.ToInt32(idLists[1]);//所要重选的技术专家数量
                int SWcount = Convert.ToInt32(idLists[2]);//所要重选的商务专家数量

                //更新专家的status=3
                bool b1 = excm.UpdateStatus(" tenderNum='"+this.txt_zbbh.Text+"'" + " and status <>3 ",0 );
                bool b2 = excm.UpdateStatus(" expertConfirmId in ("+ idList+")", 3);
                
                string projectName = this.txt_projectName.Text;
                string tenderNum = this.txt_zbbh.Text;
                int jwUid = int.Parse(this.ddljwjdy.SelectedItem.Value);
                string jwUname = this.ddljwjdy.SelectedItem.Text;

                string selExpertMajor = "";//选取的专家专业信息
                for (int i = 0; i < cblexpertMajor.Items.Count; i++)
                {
                    if (cblexpertMajor.Items[i].Selected)
                    {
                        string selValue = cblexpertMajor.Items[i].Value;
                        if (selValue == "10KV配电")
                        {
                            selValue = "s10KV配电";
                        }

                        selExpertMajor += selValue + ",";
                    }
                }
                selExpertMajor = selExpertMajor.Substring(0, selExpertMajor.LastIndexOf(","));


                if (Session["login"] != null)
                {
                    DataSet ds = Session["login"] as DataSet;

                    string randomName = ds.Tables[0].Rows[0]["user_name"].ToString();
                    int randomId = int.Parse(ds.Tables[0].Rows[0]["user_id"].ToString());
                    bool isS = false;
                    if (this.rdo_yes.Checked)
                    {
                        isS = true;
                    }

                    string msg = RandomExperts(projectName, JScount, SWcount, tenderNum, jwUid, jwUname, selExpertMajor, randomName, randomId,isS);
                    if (!string.IsNullOrEmpty(msg))
                    {
                        this.lbl_warn1.Text = msg;
                        this.lbl_warn1.Visible = true;
                    }
                    else
                    {
                        BindData();
                        this.btn_confirm.Enabled = false;
                        this.lbl_warn1.Visible = false;
                    }

                
                }

              
            }

            this.Timer1.Enabled = true;

            this.pnl_cz.Visible = false;
            this.btn_ReRandom.Visible = false;
            this.ddl_isReRandom.SelectedValue = "否";
            this.gridView.Columns[0].Visible = false;
        }

        private string GetSelIDlist()
        {
            string idlist = "";

            int jszjCount = 0;//技术专家数量
            int swzjCount = 0;//商务专家数量

            bool BxsChkd = false;
            for (int i = 0; i < gridView.Rows.Count; i++)
            {
                CheckBox ChkBxItem = (CheckBox)gridView.Rows[i].FindControl("DeleteThis");
                Label lbl_swzj = (Label)gridView.Rows[i].FindControl("lbl_swzj");
                Label lbl_jszj = (Label)gridView.Rows[i].FindControl("lbl_jszj");

                if (ChkBxItem != null && ChkBxItem.Checked)
                {
                    BxsChkd = true;
                    //#warning 代码生成警告：请检查确认Cells的列索引是否正确
                    if (gridView.DataKeys[i].Value != null)
                    {
                        if (!string.IsNullOrEmpty(lbl_swzj.Text))
                        {
                            swzjCount += 1;
                        }
                        if (!string.IsNullOrEmpty(lbl_jszj.Text))
                        {
                            jszjCount += 1;
                        }

                        idlist += gridView.DataKeys[i].Value.ToString() + ",";
                    }
                }
            }
            if (BxsChkd)
            {
                idlist = idlist.Substring(0, idlist.LastIndexOf(","));

                idlist += "|" + jszjCount + "|" + swzjCount;
            }
            return idlist;
        }

        //打印抽选结果
        protected void btn_print_Click(object sender, EventArgs e)
        {

            DataSet ds = excm.GetList("tenderNum='" + this.txt_zbbh.Text + "'");

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                int expertInfoId = Convert.ToInt32(row["expertInfoId"]);

                Maticsoft.Model.expertInfo ex = exm.GetModel(expertInfoId);

                ex.isUse = false;

                exm.Update(ex);
            }

            Response.Redirect("PrintExpert.aspx?tenderNum=" + this.txt_zbbh.Text);
            //ScriptManager.RegisterStartupScript(this.UpdatePanel1,this.GetType(),
            //    "", "<script>OpenPopWin('PrintExpert.aspx?tenderNum=" + this.txt_zbbh.Text + "','600px','800px');</script>",true);
           
        }

        protected void btn_printExpert_Click(object sender, EventArgs e)
        {

            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>OpenPopWin('PrintExpert.aspx','900px','390px');</script>");

        }

        //审核不同意后重新抽选专家
        protected void btn_confirm_re_Click(object sender, EventArgs e)
        {
            if (this.cblexpertMajor.SelectedIndex < 0)
            {
                Maticsoft.Common.MessageBox.Show(this, "请选择专家所属专业");
                return;
            }

            string projectName = this.txt_projectName.Text;
            int JScount = int.Parse(this.txt_randomJSCount.Text);//技术专家人数
            int SWcount = int.Parse(this.txt_randomSWCount.Text);//商务专家人数
            string tenderNum = this.txt_zbbh.Text;
            int jwUid = int.Parse(this.ddljwjdy.SelectedItem.Value);
            string jwUname = this.ddljwjdy.SelectedItem.Text;

            string selExpertMajor = "";//选取的专家专业信息
            for (int i = 0; i < cblexpertMajor.Items.Count; i++)
            {
                if (cblexpertMajor.Items[i].Selected)
                {
                    string selValue = cblexpertMajor.Items[i].Value;
                    if (selValue == "10KV配电")
                    {
                        selValue = "s10KV配电";
                    }

                    selExpertMajor += selValue + ",";
                }
            }
            selExpertMajor = selExpertMajor.Substring(0, selExpertMajor.LastIndexOf(","));


            if (Session["login"] != null)
            {
                DataSet ds = Session["login"] as DataSet;

                string randomName = ds.Tables[0].Rows[0]["user_name"].ToString();
                int randomId = int.Parse(ds.Tables[0].Rows[0]["user_id"].ToString());
                bool isS = false;
                if (this.rdo_yes.Checked)
                {
                    isS = true;
                }

                string msg = RandomExperts(projectName, JScount, SWcount, tenderNum, jwUid, jwUname, selExpertMajor, randomName, randomId,isS);
                if (!string.IsNullOrEmpty(msg))
                {
                    //Maticsoft.Common.MessageBox.Show(this, msg);
                    this.lbl_warnNo.Text = msg;
                    this.pnl_no.Visible = true;
                }
                else
                {
                    BindData();
                    this.pnl_no.Visible = false;
                }
            }
        }

    }
}